<template>
	<div class="updateUserInfo">
		<div class="upload">
			<div class="image">
				<u-image style="margin: 0 auto" :showLoading="true" :src="userInfo.avatar" shape="circle" width="100px"
					height="100px" @click="previewImage(userInfo.avatar)"></u-image>
			</div>
			<divider :lineHeight="`10`" :lineColor="`#f8f8f8`"></divider>
			<u-button type="primary" text="更换头像" style="width: 180rpx" @click="uploadImage"></u-button>
			<divider :lineHeight="`10`" :lineColor="`#f8f8f8`"></divider>
			<u--input placeholder="请输入昵称" border="surround" clearable v-model="userInfo.nickname"></u--input>
			<divider :lineHeight="`20`" :lineColor="`#f8f8f8`"></divider>
			<u-row justify="space-between" gutter="10">
				<u-col span="6">
					<u-button type="primary" text="保存" @click="saveUserInfo"></u-button>
				</u-col>
				<u-col span="6">
					<u-button type="primary" color="#66CC33" text="重置" @click="resetUserInfo"></u-button>
				</u-col>
			</u-row>
		</div>
	</div>
</template>

<script>
	import divider from "@/components/divider/divider";
	import {
		upload_image,
		updateUserInfo
	} from "@/common/api/index";
	export default {
		name: "updateUserInfo",
		components: {
			divider,
		},
		data() {
			return {};
		},
		computed: {
			userInfo() {
				return this.$store.state.userInfo;
			},
		},
		created() {
			console.log();
		},
		methods: {
			uploadImage() {
				const that = this;
				uni.chooseImage({
					count: 1,
					sourceType: ["album", "camera"],
					crop: "width:80px;height:80px",
					success: async (res) => {
						console.log(res, "success");
						let result = await upload_image({
							filePath: res.tempFilePaths[0],
						});
						if (result.code === 1) {
							that.userInfo.avatar = result.data.uri;
						} else {
							that.showMsg(res.msg);
						}
						console.log(result, "upload_image");
					},
					complete: (res) => {
						console.log(res, "complete");
					},
				});
			},
			async saveUserInfo() {
				let formData = {
					nickname: this.userInfo.nickname,
					avatar: this.userInfo.avatar,
				};
				let result = await updateUserInfo(formData);

				if (result.code === 1) {
					this.showMsg("修改成功");
					setTimeout(() => {
						uni.switchTab({
							url: "/pages/mine/mine",
						});
					}, 1500);
				} else {
					this.showMsg(res.msg);
				}
			},
			resetUserInfo() {
				this.userInfo = uni.getStorageSync("userInfo");
			},
			previewImage(url) {
				uni.previewImage({
					urls: [url],
					longPressActions: {
						success: function(data) {
							console.log(data);
						},
						fail: function(err) {
							console.log(err.errMsg);
						},
					},
				});
			},
		},
	};
</script>

<style scoped lang="scss">
	.updateUserInfo {
		padding: 50rpx;
		text-align: center;
		background-color: #f8f8f8;
		height: 100vh;
		box-sizing: border-box;

		.upload {
			.image {
				display: flex;
				justify-content: center;
			}
		}
	}
</style>